package com.hmdp.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.service.IShopTypeService;
import com.hmdp.utils.RedisConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TTL;
import static com.hmdp.utils.RedisConstants.CACHE_TYPE_TTL;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@RestController
@RequestMapping("/shop-type")
@Slf4j
public class ShopTypeController {
    @Resource
    private IShopTypeService typeService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("list")
    public Result queryTypeList() {
        log.info("get商户类型列表");
        // 1. 查询缓存中是否有
        String key = RedisConstants.SHOP_TYPE_KEY + "list";
        String typeListStr = stringRedisTemplate.opsForValue().get(key);
        // 2. 如果有直接返回
        if(StrUtil.isNotBlank(typeListStr)) {
            List<ShopType> typeList = JSONUtil.toList(typeListStr, ShopType.class);
            return Result.ok(typeList);
        }
        // 3. 没有查询数据库
        List<ShopType> typeList = typeService
                .query().orderByAsc("sort").list();
        // 4. 保存到redis缓存
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(typeList));
        stringRedisTemplate.expire(key, CACHE_TYPE_TTL, TimeUnit.MINUTES);
        // 5. 返回结果
        return Result.ok(typeList);
    }
}
